package com.ruoyi.market.controller;

import com.ruoyi.bizsys.domain.AppUser;
import com.ruoyi.bizsys.domain.MarketLinkCreditLog;
import com.ruoyi.bizsys.domain.MarketPageActionLog;
import com.ruoyi.bizsys.service.IAppUserService;
import com.ruoyi.bizsys.service.IApplyContactsService;
import com.ruoyi.bizsys.service.IMarketLinkCreditLogService;
import com.ruoyi.bizsys.service.IMarketPageActionLogService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.HttpContextUtils;
import com.ruoyi.market.config.MarketConfig;
import com.ruoyi.market.service.IMarketService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Author: Jamnsin
 * @Date: 2021/5/3 11:28 上午
 */
@Slf4j
@RestController
@RequestMapping("/market")
public class ApiController {

    public static final String LINK_CREDIT_TYPE_NEW = "new";
    public static final String LINK_CREDIT_TYPE_ACTIVE = "active";

    @Autowired
    IMarketLinkCreditLogService marketLinkCreditLogService;

    @Autowired
    IAppUserService appUserService;

    @Autowired
    IMarketPageActionLogService marketPageActionLogService;

    @Autowired
    MarketConfig marketConfig;

    @Autowired
    IApplyContactsService contactsService;

    @Autowired
    IMarketService marketService;

    @Log(title = "同步客户通讯录", businessType = BusinessType.API)
    @GetMapping("/contact/list")
    public AjaxResult fetchContactList(HttpServletRequest request) {
        String level1Num = request.getParameter("level1");
        String level2Num = request.getParameter("level2");
        String level3Num = request.getParameter("level3");
        return AjaxResult.success(marketService.getCustContacts(level1Num, level2Num, level3Num));
    }

    @Log(title = "同步客户状态", businessType = BusinessType.API)
    @GetMapping("/cust/status")
    public AjaxResult fetchCustStatus() {
        return AjaxResult.success(marketService.fetchCustStatus());
    }

    @Log(title = "落地页按钮事件记录", businessType = BusinessType.API)
    @PostMapping("/market_page_action_log")
    public AjaxResult add(@RequestBody MarketPageActionLog marketPageActionLog) {
        if (null != marketPageActionLog.getPageReqId()) {
            marketPageActionLog.setId(null);
            marketPageActionLog.setCreateTime(new Date());
            int insertResult = marketPageActionLogService.insertMarketPageActionLog(marketPageActionLog);
            if (insertResult > 0) {
                return AjaxResult.success();
            }
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    @Log(title = "落地页跳转记录", businessType = BusinessType.API)
    @GetMapping("/linkCredit")
    public ModelAndView linkCredit() {
        log.info("落地页埋点跳转接口调用");
        // 接收到请求，记录请求内容
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        String phoneNumber = request.getParameter("phoneNumber");
        String type = request.getParameter("type");

        //记录
        MarketLinkCreditLog marketLinkCreditLog = new MarketLinkCreditLog();
        marketLinkCreditLog.setCreateTime(new Date());
        marketLinkCreditLog.setPhone(phoneNumber);

        //记录用户访问时间
        if (StringUtils.isNotBlank(phoneNumber) && phoneNumber.startsWith("234")) {
            phoneNumber = phoneNumber.substring(3);
            if (phoneNumber.length() == 10) {
                phoneNumber = "0" + phoneNumber;
            }
            AppUser userQuery = new AppUser();
            userQuery.setCountryCode("+234");
            userQuery.setPhone(phoneNumber);
            List<AppUser> userList = appUserService.selectAppUserList(userQuery);
            if (userList.size() > 0) {
                AppUser user = userList.get(0);
                marketLinkCreditLog.setUserId(user.getUserId() + "");
                marketLinkCreditLog.setUserUuid(user.getUserUuid());
                if (StringUtils.isBlank(type)) {
                    type = LINK_CREDIT_TYPE_ACTIVE;
                }
            } else {
                if (StringUtils.isBlank(type)) {
                    type = LINK_CREDIT_TYPE_NEW;
                }
            }
        }
        marketLinkCreditLog.setPageType(type);
        marketLinkCreditLogService.insertMarketLinkCreditLog(marketLinkCreditLog);

        //跳转
        String targetUrl = marketConfig.getNormal();
        if (StringUtils.isNotBlank(type)) {
            if (LINK_CREDIT_TYPE_NEW.equals(type)) {
                targetUrl = marketConfig.getGetNew();
            } else if (LINK_CREDIT_TYPE_ACTIVE.equals(type)) {
                targetUrl = marketConfig.getActive();
            }
        }
        targetUrl = marketConfig.getHost() + targetUrl + "?channel=market" + "&reqId=" + marketLinkCreditLog.getId();
        log.info("落地页埋点最终转发跳转地址：" + targetUrl);
        ModelAndView m = new ModelAndView("redirect:" + targetUrl);//正常跳转
        return m;
    }
}